#include <stdio.h> 
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>

#include "sm4.h"
#include "key.h"
#include "common_func.h"
#include "core_time.h"

//BSP板级支持包所需全局变量
unsigned long UART_BASE = 0xbf000000;					//UART16550的虚地址
unsigned long CONFREG_TIMER_BASE = 0xbf20f100;			//CONFREG计数器的虚地址
unsigned long CONFREG_CLOCKS_PER_SEC = 50000000L;		//CONFREG时钟频率
unsigned long CORE_CLOCKS_PER_SEC = 33000000L;			//处理器核时钟频率

int main(int argc, char** argv)
{
	printf("\nHello Loongarch32r SM4 inkey!\n");
	
	//delay_ms(1000);

	uint32_t ret = 0;
	uint8_t key[16] 	= {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 
					       0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10};
	uint8_t plain[16] 	= {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 
					       0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10};	   
	uint8_t chiper[16] 	= {0x68, 0x1e, 0xdf, 0x34, 0xd2, 0x06, 0x96, 0x5e, 
						   0x86, 0xb3, 0xe9, 0x4f, 0x53, 0x6e, 0x42, 0x46};		   
	uint8_t result[16]  = {0};
	char *pin = "qwer1234";
	
	printf("key = ");
	for(int i = 0; i < 16; i++)
	{
		printf("0x%02x ", key[i]);
	}
	printf("\n");
	
	//key---------------------------------------------------
	ret = write_key(KEY_TYPE_SM4, 0, pin, NULL, NULL, key);
	if(ret)
	{
		printf("Write SM4 key faild with ret = 0x%X!\n", ret);
	}
	else
	{
		printf("Write SM4 key success.\n");
	}
	ret = access_key(KEY_TYPE_SM4, 0, pin);
	if(ret)
	{
		printf("Access SM4 key faild with ret = 0x%X!\n", ret);
	}
	else
	{
		printf("Access SM4 key success.\n");
	}
	
	//enc------------------------------------------------
	printf("Start init SM4 in ENC mode.\n");
	ret = sm4_init_inkey(0);
	if(ret)
	{
		printf("SM4 init faild in ENC mode!\n");
	}
	ret = sm4_enc_dec(plain, result);
	if(ret)
	{
		printf("SM4 enc faild!\n");
	}
	
	printf("plain = ");
	for(int i = 0; i < 16; i++)
	{
		printf("0x%02x ", plain[i]);
	}
	printf("\n");
	printf("result = ");
	for(int i = 0; i < 16; i++)
	{
		printf("0x%02x ", result[i]);
	}
	printf("\n");
	if (memcmp(chiper, result, 16) == 0) 
	{
        printf("Enc success.\n");
    } else {
        printf("Enc Faild.\n");
    }
	//enc------------------------------------------------
	
	
	sm4_clear();
	memset(result, 0x0, 16);
	
	//dec------------------------------------------------
	printf("Start init SM4 in DEC mode.\n");
	ret = sm4_init_inkey(1);
	if(ret)
	{
		printf("SM4 init faild in DEC mode!\n");
	}
	ret = sm4_enc_dec(chiper, result);
	if(ret)
	{
		printf("SM4 dec faild!\n");
	}
	
	printf("chiper = ");
	for(int i = 0; i < 16; i++)
	{
		printf("0x%02x ", chiper[i]);
	}
	printf("\n");
	printf("result = ");
	for(int i = 0; i < 16; i++)
	{
		printf("0x%02x ", result[i]);
	}
	printf("\n");
	if (memcmp(plain, result, 16) == 0) 
	{
        printf("Dec success.\n");
    } else {
        printf("Dec Faild.\n");
    }
	//dec------------------------------------------------
	
	release_key(KEY_TYPE_SM4, 0);
	
	printf("SM4 inkey test finished!\n");

	return 0;
}